package opensource.web.servlets.projects;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import opensource.web.util.db.DBM;
import opensource.web.util.json.JsonA;
import opensource.web.util.json.JsonO;

public class ViewProjectsServlet extends HttpServlet{

	/**
	 * this is a demo: view all projects, output the data by json.
	 */
	private static final long serialVersionUID = 1L;
	
	public void service(HttpServletRequest request,HttpServletResponse response)
			throws IOException, ServletException {
		
		request.setCharacterEncoding("UTF-8");
		
		response.setCharacterEncoding("UTF-8");
		
		DBM dbm = DBM.getInstance();
		
		String sql = "select * from projects order by type desc";
		
		try {
			ResultSet set = dbm.singleQuery(sql);
			JsonA jsonA = new JsonA();
			while(set.next()){
				int type = set.getInt(2);
				String name = set.getString(3);
				String creator = set.getString(4);
				String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(set.getDate(5));
				int number = set.getInt(6);
				boolean isactive = set.getInt(7)==1?true:false;
				String brief = set.getString(8);
				JsonO jsonO = new JsonO();
				jsonO.put("type", String.valueOf(type));
				jsonO.put("name", name);
				jsonO.put("creator", creator);
				jsonO.put("date",date);
				jsonO.put("number", String.valueOf(number));
				jsonO.put("isactive", String.valueOf(isactive));
				jsonO.put("brief", brief);
				jsonA.append(jsonO);
			}
			PrintWriter out = response.getWriter();
			out.print(jsonA.getString());
			out.flush();
			out.close();
			System.out.println("Request is handled by ViewProjectsServlet.");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
